package common.util.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @Author: nxs@winning.com.cn
 *
 * @Description:  文件上传工具类
 *
 * @Date: 2018-08-31 15:21:47
 *
 *
 **/
public class FileUtils {





    /**
     *
     * @param file 文件
     * @param uploadPath 文件存放路径
     * @param fileName 源文件名
     * @return
     */
    public static boolean upload(MultipartFile file, String uploadPath, String fileName){


        String realUploadPath =  new FileUtils().getUploadPath(uploadPath);
        //当前目录位置+上传路径+文件名
        String realPath = realUploadPath + "/" + fileName;

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdir();
        }

        try {
            //保存图片或文件
            file.transferTo(dest);
            return true;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }


    /**
     * @Author: nxs@winning.com.cn
     *
     * @Description:  获取当前服务器 上传的完整路径
     *
     * @Date: 2018-09-03 17:08:31
     *
     *
     **/
    public String getUploadPath(String uploadPath){
        File path = null;
        /*try {
//            path = new File(ResourceUtils.getURL("classpath:").getPath());
//            path = new File(ResourceUtils.getURL("").getPath());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        path = new File(System.getProperty("catalina.home"));
        if(!path.exists()) {
            path = new File("");
        }
        //当前路径
        System.out.println("path:"+path.getAbsolutePath());

        //如果上传目录为/static/images/upload/，则可以如下获取：
        File upload = new File(path.getAbsolutePath(),uploadPath);
        if(!upload.exists()) upload.mkdirs();
        //上传的路径
        System.out.println("upload url:"+upload.getAbsolutePath());
        return upload.getAbsolutePath();
    }







}
